package com.etalk.crm.serviceImpl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.etalk.crm.dao.TextBooksMapper;
import com.etalk.crm.dao.TextbooksCategoryMapper;
import com.etalk.crm.pojo.TextbookesCategory;
import com.etalk.crm.pojo.Textbooks;
import com.etalk.crm.service.TextbooksService;
import com.etalk.crm.utils.OssGetObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.util.stream.Collectors.toList;

/**
 * @author Terwer
 * @date 2018/10/24 15:13
 * @version 1.0
 * @Description 教材
 **/
@Service
public class TextbooksServiceImpl implements TextbooksService {
    private static final Logger logger = LogManager.getLogger(TextbooksServiceImpl.class);

    @Resource
    private TextBooksMapper textBooksMapper;
    @Resource
    private TextbooksCategoryMapper textbooksCategoryMapper;

    @Override
    public PageInfo selectTextbooks(Map<String, Object> map, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Textbooks> list = textBooksMapper.selectTextbooks(map);
        // 分页信息
        return new PageInfo<>(list);
    }

    @Override
    public PageInfo selectTextbooksByThirdId(Integer thirdId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Textbooks> list = textBooksMapper.selectTextbooksByThirdId(thirdId);
        // 分页信息
        return new PageInfo<>(list);
    }

    /**
     * 查询教材类别，受套餐设置的匹配限制
     * @param map
     * @return
     */
    @Override
    public List<TextbookesCategory> searchTextbooksCategroyBySearch(Map<?, ?> map) {
        return textbooksCategoryMapper.searchTextbooksCategoryBySearch(map);
    }

    @Override
    public PageInfo getTextbooksListByKnowledgeId(Integer knowledgeId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Textbooks> list = textBooksMapper.getTextbooksListByKnowledgeId(knowledgeId);
        // 分页信息

        return new PageInfo<>(list);
    }

    @Override
    public List<Map> showTextbooksPageList(String strUrl) {
        // 教材页码数据
        List<Map> resultList = new ArrayList<>();
        String jsonContent = OssGetObject.getCfgJson(strUrl);
        if (StringUtil.isNotEmpty(jsonContent)) {
            JSONArray jsona = JSON.parseArray(jsonContent);
            for (int i = 0; i < jsona.size(); i++) {
                String str = ((JSONObject) jsona.get(i)).getString("t");
                if ("f".equals(str)) {
                    str = ((JSONObject) jsona.get(i)).getString("n");
                    String page = str.substring(0, str.indexOf("."));
                    // 组装结果
                    Map<String,Object> pageMap = new HashMap<>(2);
                    pageMap.put("id", i);
                    pageMap.put("name", page);
                    resultList.add(pageMap);
                }
            }
        }
        return resultList;
    }

    @Override
    public JSONArray getConfigByTextbooksId(Integer textbooksId) {
        String address = textBooksMapper.selectAddressByTextbooksId(textbooksId);
        if (address.lastIndexOf("/") == address.length() - 1) {
            address += "cfg.json";
        } else {
            address += "/cfg.json";
        }
        String jsonContent = OssGetObject.getCfgJson(address);
        JSONArray jsona = null;
        if (StringUtil.isNotEmpty(jsonContent)) {
            jsona = JSON.parseArray(jsonContent);
        }
        return jsona;
    }

    /**
     * 获取教材目录和页码信息
     * @param id 教材id
     * @return
     */
    @Override
    public Map<String,Object> searchTextbookAddressById(Integer id) {
        Map<String,Object>  map = new HashMap<>(2);
        String address = textBooksMapper.selectAddressByTextbooksId(id);
        map.put("address",address);
        if (address.lastIndexOf("/") == address.length() - 1) {
            address += "cfg.json";
        } else {
            address += "/cfg.json";
        }
        List<String> list = new ArrayList<>();
        String jsonContent = OssGetObject.getCfgJson(address);
        if (StringUtil.isNotEmpty(jsonContent)) {
            for (Object o : JSON.parseArray(jsonContent)) {
                String str = ((JSONObject) o).getString("t");
                if ("f".equals(str)) {
                    str = ((JSONObject) o).getString("n");
                    list.add(str.substring(0, str.indexOf(".")));
                }
            }
            map.put("pages",list);
        }
        return map;
    }

    @Override
    public int getTextbooksIdxByPage(JSONArray jsona, String pageName) {
        int idx = -1;
        for (int i = 0; i < jsona.size(); i++) {
            String str = ((JSONObject) jsona.get(i)).getString("t");
            if ("f".equals(str)) {
                str = ((JSONObject) jsona.get(i)).getString("n");
                String page = str.substring(0, str.indexOf("."));
                // 检测索引
                if (pageName.equals(page)) {
                    idx = i;
                    break;
                }
            }
        }
        return idx;
    }

    @Override
    public List<Map> getNotImportedList(List<Map> dataList) {
        logger.info("dataList:" + dataList);
        // 原数据去重
        logger.info("导入前数据处理");
        dataList = dataList.stream().distinct().map(Map.class::cast).collect(toList());
        // 数据库去重
        List<Map> existList = textBooksMapper.getExistList(dataList);
        logger.info("existList:" + existList);
        List<Map> resultList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(existList)) {
            // 取出dataList里面不包含existList的剩下的元素
            for (Map x : dataList) {
                boolean exist = false;
                for (Map y : existList) {
                    boolean flag1 = Integer.parseInt(x.get("textbooksPage").toString()) == Integer.parseInt(y.get("textbooksPage").toString());
                    boolean flag2 = Integer.parseInt(x.get("textbooksId").toString()) == Integer.parseInt(y.get("textbooksId").toString());
                    boolean flag3 = Integer.parseInt(x.get("qknowledgeId").toString()) == Integer.parseInt(y.get("qknowledgeId").toString());
                    boolean flag4 = Integer.parseInt(x.get("knowledgePoint").toString()) == Integer.parseInt(y.get("knowledgePoint").toString());
                    if ((flag1 && flag2 && flag3 && flag4)) {
                        exist = true;
                        break;
                    }
                }
                if (!exist) {
                    resultList.add(x);
                }
            }
        } else {
            resultList = dataList;
        }
        logger.info("resultList:" + resultList);
        return resultList;
    }

    /**
     * 根据父id查询教材类别，不受套餐限制
     * @param parentId 父id
     * @return 子类别列表
     */
    @Override
    public List<TextbookesCategory> searchTextbookCategoryByParentId(int parentId){
        return textbooksCategoryMapper.selectTextbooksCategoryByParentId(parentId);
    }

    /**
     * 根据教材分类id查询其所属教材列表，不分页
     * @param thirdId 第三级教材分类id
     * @return 教材列表
     */
    @Override
    public List<Textbooks> selectTextbooksListByThirdId(Integer thirdId) {
        List<Textbooks> list = textBooksMapper.selectTextbooksByThirdId(thirdId);
        // 分页信息
        return list;
    }
}
